<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Project extends REST_Controller {

    function __construct(){  
        
        parent::__construct();  
        $this->returnInfo = lang('returnInfo');
        $this->rdata['returnNo'] = '0000';
        $this->rdata['returnInfo'] = $this->returnInfo['0000'];
        $this->rdata['returnTime'] = time();
        $this->rdata['returnData'] = (object)array();
    }

    public function index_get() {

        echo 'welcome.';
    }

    public function list_get(){

        $where = array();

        $type = $this->get('type') === FALSE?-1:intval($this->get('type'));
        if (!$type || !is_numeric($type)) {

            $type = 1;
        } 

        if ($type != '-1') {

            $where = array('type'=>$type);
        }

        //状态字段 默认1 -1为全部
        $status = $this->get('status') === FALSE?-1:intval($this->get('status'));
        if(!$status || !is_numeric($status)){

            $status = 1;
        }

        //前端转台1 招标中 2 还款中 3已还清 -1全部 
        //转换成数据库中的项目状态条件
        if ($status != '-1') {
            switch ($status) {
                case 1:
                    $where["in"] = array("projectstatus",array(1,5));
                    break;
                case 2:
                    $where["projectstatus"] = 2;
                    break;
                case 3:
                    $where["in"] = array("projectstatus",array(3,4));
                    break;

                default:
                   
                    break;
            }
        }

        $where['audit'] = 1;

        //标签字段 默认-1 -1为全部 tag=1为新手标
        $tags = $this->get('tags') === FALSE?-1:intval($this->get('tags'));
        if ($tags != -1) {
            $where['tags'] = $tags?1:0;
        }

        //标签字段 默认-1 -1为全部 flag=1为推荐标 
        $flag = $this->get('flag') === FALSE?-1:intval($this->get('flag'));
        if ($flag != -1) {
            $where['flag'] = $flag?1:0;

            //如果是推荐标而且没有指定是否新手标 那么就选择非新手标
            if (!isset($where['tags']) && $where['flag'] == 1) {

            	$where['tags'] = 0;
            }
        }

        $sort = $this->get('sort');

        switch ($sort) {
            case 'rate':
                $order = array("rate"=>"desc");
                break;
            case 'cycle':
                $order = array("days"=>"desc");
                break;
            case 'percent':
                $order = array("percent"=>"desc");
                break;
            default:
                $order = array("projectstatus"=>"asc","start_at"=>"asc");
                break;
        }

        //利息区间 字典 默认1
        $this->load->model("project_filter_model","mpfi",'default');
        $rate = intval($this->get('rate'));
        if(!$rate || !is_numeric($rate)){

            $rate = -1;
        }else if ($rate != -1) {
            
            $rate_arr = $this->mpfi->get_one(array("identify"=>"rate","id"=>$rate));

            if ($rate_arr) {
                if ($rate_arr['min']) {
                    $where['rate >='] = $rate_arr['min'];
                }

                if ($rate_arr['max']) {
                    $where['rate <'] = $rate_arr['min'];
                }
            }else{
                $rate = -1;
            }
        }
        
        //周期字段 字典 默认1
        $cycle = intval($this->get('cycle'));
        if(!$cycle || !is_numeric($cycle)){

            $cycle = -1;
        }else if ($cycle != -1) {
            $cycle_arr = $this->mpfi->get_one(array("identify"=>"cycle","id"=>$cycle));

            if ($cycle_arr) {
                if ($cycle_arr['min']) {
                    $where['days >='] = $cycle_arr['min'];
                }

                if ($cycle_arr['max']) {
                    $where['days <'] = $cycle_arr['max'];
                }
            }
        }

        //页数 默认1
        $page = intval($this->get('page'));
        if (!$page || !is_numeric($page)) {

            $page = 1;
        }    

        //每页尺寸 默认1
        $size = intval($this->get('size'));
        if(!$size || !is_numeric($size)){

            $size = 10;
        }


        $this->load->model('project_model','mpro');

        $limit  = $size;
        $start  = ($page-1)*$size;
        $fields = 'id,status,title,rate,days,money,method,have_money,min_money,pwd,tags,flag,(case projectstatus when 5 then 1 else  projectstatus end) as projectstatus,(have_money / money) as percent,start_at';
        $table  = FALSE;
        $expire = 60; //stroing for a minute;
        $total  = $this->mpro->get_count_all_cache($where,FALSE,$expire);
        $result = $this->mpro->get_list_where_cache($limit,$start,$order,$where,$fields,FALSE,$expire);
        //数据库错误 
        if (!$result) {
            $this->response($this->rdata);
        }

        $list = array();
        $method_arr = array(0=>'按日计息，到期一次性还本付息',1=>'按日计息，按月付息，到期还款');
        $projectstatus_arr = array(1=>1,2=>2,3=>3,4=>3,5=>1);//6是还未开始 但是仅在start_at还未开始时有效
        $now = time();
        foreach ($result as $key => $value) {
            $tmp = array();
            $tmp['id'] = $value['id'];

            //判断项目是否开始
            $start_at = strtotime($value['start_at']);
            if ($start_at && $start_at > $now) {
                $projectstatus = 0;
            }else{
                $projectstatus = $projectstatus_arr[$value['projectstatus']];
            }
            
            $tmp['status'] = $projectstatus;
            $tmp['title'] = $value['title'];
            $tmp['rate'] = $value['rate'];
            $tmp['tags'] = $value['tags']?"新手专享":"";
            $tmp['flag'] = $value['flag'];
            $tmp['cycle'] = $value['days'];
            $tmp['investment'] = $value['money'];
            $tmp['money'] = $value['money'];
            $tmp['method'] = $method_arr[$value['method']];
            $tmp['have_money'] = $value['have_money'];
            $tmp['start_at'] = $value['start_at'];
            $tmp['note'] = $value['min_money'].'起投';
            $tmp['need_pwd'] = $value['pwd']?1:0;
            $tmp['note_list'] = array();
            if ($value['tags']) {

                $tmp['note_list'][] = '新手专享';
            }
            $tmp['note_list'][] = $value['min_money'].'起投';
            $tmp['note_list'][] = $method_arr[$value['method']];
            $list[] = $tmp;
        }

        $this->rdata['returnData']->type = $type;
        $this->rdata['returnData']->list = $list;
        $this->rdata['returnData']->total = $total;
        $this->rdata['returnData']->page = $page;
        $this->response($this->rdata);
    }

    public function investmentList_get(){

        $pid = $this->get("pid");
        if (!$pid || !is_numeric($pid) || $pid <= 0) {
            $this->rdata['returnNo'] = '0011';
            $this->rdata['returnInfo'] = $this->returnInfo['0011'];
            $this->response($this->rdata);
        }

        $page = $this->get("page");
        if (!$page || !is_numeric($page) || $page <= 0) {
            $page = 1;
        }

        $size = $this->get("size");
        if (!$size || !is_numeric($size) || $size <= 0) {
            $size = 10;
        }

        $this->load->model('union_investment_model','muni',"default");
        $limit  = $size;
        $start  = ($page-1)*$size;
        $fields = 'union_investment.pid,account.nickname,union_investment.money,union_investment.create_at';
        $table  = FALSE;
        $expire = 60; //stroing for a minute;
        $where = array("pid"=>$pid);
        $order = array("union_investment.create_at"=>"asc");
        
        $total = 0;
        $total  = $this->muni->get_list_join_account_count($where,FALSE,$expire);
        $result = $this->muni->get_list_join_accout($limit,$start,$order,$where,$fields,FALSE,$expire);
        //数据库错误 
        $list = array();
        $page = $page;
        if (!$result) {
            $this->rdata['returnData']->list = $list;
            $this->rdata['returnData']->total = $total;
            $this->rdata['returnData']->page = $page;
            $this->response($this->rdata);
        }

        $list = array();
        foreach ($result as $key => $value) {
            $tmp = array();
            $tmp['pid'] = $value['pid'];
            $tmp['nickname'] = $value['nickname'];
            $tmp['money'] = $value['money'];
            $tmp['create_at'] = $value['create_at'];
            $list[] = $tmp;
        }

        $this->rdata['returnData']->list = $list;
        $this->rdata['returnData']->total = $total;
        $this->rdata['returnData']->page = $page;
        $this->response($this->rdata);
    }


    public function info_get(){
        $id = intval($this->get('id'));
        if (!$id || !is_numeric($id)) {

            $this->rdata['returnNo'] = '0011';
            $this->rdata['returnInfo'] = $this->returnInfo['0011'];
            $this->response($this->rdata);
        }
        $where = array();
        $where['audit'] = 1;
        $where['id'] = $id;
        $this->load->model("project_model","mpro");
        $result = $this->mpro->get_one_where_cache($where,FALSE,30);

         //不论是操作错误还是数据库查询不到 都认为是条目不存在
        if (!$result) {
            $this->response($this->rdata);
        }
        $method_arr = array(0=>'按日计息，到期一次性还本付息',1=>'按日计息，按月付息，到期还款');
        $projectstatus_arr = array(1=>1,2=>2,3=>3,4=>3,5=>1);

        //判断项目是否开始
        $start_at = strtotime($result['start_at']);
        if ($start_at && $start_at > time()) {
            $projectstatus = 0;
        }else{
            $projectstatus = $projectstatus_arr[$result['projectstatus']];
        }

        //最大金额的检查 必须要在成功发送记录之后才存入redis 在存在redis时不可删除 因为当时存在一笔交易请求 而在第一次时 错误就应该删除
        if ($user_id = $this->session->userdata("UAID")) {
            $mkey = 'Cache:freeze:funds:investment:max_money'.$user_id.'_'.$id;
            if (!$investment_already = $this->cache->get($mkey)) {

                //如果redis中没有记录  总投资额从数据库中取 当前的总投资额=历史投资(数据库)+本次提交的投资额
                $this->load->model("investment_model","minvest",'default');
                $where = array('aid'=>$user_id,"pid"=>$id);
                $fields = "SUM(money) as money";
                $result_invesment = $this->minvest->get_one($where,$fields);
                $investment_already = $result_invesment['money']?$result_invesment['money']:0;
                $this->cache->save($mkey,$investment_already,1000);
            }
        }else{
            $investment_already = 0;
        }
        

        $this->rdata['returnData']->id          = $result['id'];
        $this->rdata['returnData']->title       = $result['title'];
        $this->rdata['returnData']->status      = $projectstatus;
        $this->rdata['returnData']->title_seo   = $result['title_seo'];
        $this->rdata['returnData']->tags        = $result['tags']?"新手专享":"";
        $this->rdata['returnData']->flag        = $result['flag'];
        $this->rdata['returnData']->rate        = $result['rate'];
        $this->rdata['returnData']->cycle       = $result['days'];
        $this->rdata['returnData']->need_pwd    = $result['pwd']?1:0;
        $this->rdata['returnData']->money       = $result['money'];
        $this->rdata['returnData']->have_money  = $result['have_money'];
        $this->rdata['returnData']->min_money   = $result['min_money'];
        $this->rdata['returnData']->step_money  = $result['step_money'];
        $this->rdata['returnData']->start_at    = $result['start_at'];
        $this->rdata['returnData']->method      = $method_arr[$result['method']];
        $this->rdata['returnData']->detail      = $result['detail'];
        $this->rdata['returnData']->max_money   = (int)$result['max_money'];
        $this->rdata['returnData']->filled_money= (int)$investment_already;
        $this->rdata['returnData']->loan_info   = $result['loan_info'];
        $this->rdata['returnData']->measure     = $result['measure'];
        $this->rdata['returnData']->agreement   = $result['agreement'];

        $this->response($this->rdata);
    }



    public function pwdValidate_post(){


        if (!$uinfo = $this->session->userdata('UAID')) {

            $this->rdata['returnNo'] = '0013';
            $this->rdata['returnInfo'] = $this->returnInfo['0013'];
            $this->response($this->rdata);
        }


        $id = intval($this->post('id'));
        if (!$id || !is_numeric($id)) {

            $this->rdata['returnNo'] = '0011';
            $this->rdata['returnInfo'] = $this->returnInfo['0011'];
            $this->response($this->rdata);
        }

        $pwd = $this->post('pwd');
        if (!$pwd) {

            $this->rdata['returnNo'] = '0011';
            $this->rdata['returnInfo'] = $this->returnInfo['0011'];
            $this->response($this->rdata);
        }

        //如果redis中已经存了验证通过的标记 直接返回
        $pre = 'Cache:Lock:user:pwdValidate_post:'.$uinfo.'_'.$id;

        //否则对比密码 用过后标记存入redis
        $this->load->model("project_model","mpro");
        $result = $this->mpro->get_one_id_cache($id);
        if (passwd($pwd) != $result['pwd']) {

            $this->rdata['returnInfo'] = '约标密码错误';
            $this->rdata['returnNo'] = '3311';
        }else{
            
            $this->cache->save($pre,1,86400);
        }

        $this->response($this->rdata);
    }


    protected function _getCacheKey($method,$id){
        $pre_key = "Cache:Lock:project:$method:$id";
        return $pre_key;
    }
}